/*
 * @lc app=leetcode.cn id=105 lang=cpp
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    TreeNode *digui(vector<int> &preorder, vector<int> &inorder, int lpre, int rpre, int lin, int rin)
    {
        if (lpre > rpre || lin > rin)
            return nullptr;
        TreeNode *root = new TreeNode(preorder[lpre]);
        if (lpre == rpre)
            return root;

        for (int i = lin; i <= rin; i++)
        {
            if (inorder[i] == preorder[lpre])
            {
                root->left = digui(preorder, inorder, lpre + 1, lpre + i - lin, lin, i - 1);
                root->right = digui(preorder, inorder, lpre + i - lin + 1, rpre, i + 1, rin);

                return root;
            }
        }
        return nullptr;
    }
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
    {
        return digui(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
    }
};
// @lc code=end
